﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Diagnostics;
using Cherry.Agile.ServiceModel.Runtime;

namespace Cherry.Agile.ServiceModel.Monitor {
    sealed class StateDispatcher {
        static string __remoteaddress;
        static string __selfAddress;
        static string __name;
        static Timer __timer = null;
        
        static StateDispatcher() {
            if (!Config.RempServiceModelSection.Current.Monitor.Enable
                && Config.RempServiceModelSection.Current.Service.Usage == "normal")
                return;
            __remoteaddress = Config.RempServiceModelSection.Current.Monitor.Address;
            __selfAddress = Config.RempServiceModelSection.Current.Service.Address ?? 
                            System.Configuration.ConfigurationManager.AppSettings["service.address"];

            if (string.IsNullOrEmpty(__remoteaddress)) {
                Trace.TraceWarning("monitor address is null.");
                return;
            }
            __name = Config.RempServiceModelSection.Current.Service.Name??
                    System.Configuration.ConfigurationManager.AppSettings["service.name"];

            __timer = new Timer();
            var interval = Config.RempServiceModelSection.Current.Monitor.Interval;
            interval = Math.Max(5, interval);
            interval = Math.Min(15, interval);
            __timer.Interval = interval * 1000;
            __timer.Elapsed += new ElapsedEventHandler(__timer_Elapsed);

        }

        public static void Start() {
            if (__timer == null)
                return;
            __timer.Start(); 
            Trace.TraceInformation("Monitor\tdispatcher service started.");
        }

        public static void Stop() {
            if (__timer == null)
                return; 
            __timer.Stop(); 
            Trace.TraceInformation("Monitor\tdispatcher service stoped.");
        }
        static bool _callling =false;
        static void __timer_Elapsed(object sender, ElapsedEventArgs e) {
            if (_callling)
                return;
            _callling = true;
            var client = ClientFactory.Current.CreateClient<IMonitorService>(RuntimeUnity.GetDefeaultBinding(),__remoteaddress);
            try {
                client.Notify(__selfAddress,__name,DateTime.Now.ToLongDateString());
            } catch {

            } finally {
                var chl = client as System.ServiceModel.IClientChannel;
                if (chl != null) {
                    if (chl.State == System.ServiceModel.CommunicationState.Faulted) {
                        chl.Abort();
                    } else
                        chl.Close();
                }
            }
            _callling = false;

        }


    }
}
